<script lang="ts" setup>
import { ref, h, reactive, onMounted,onBeforeMount } from "vue";
import { ReVxeGrid } from "@/components/ReVxeTable";
import { VxeGridPropTypes, VxeUI } from "vxe-table";
import { VxeFormProps, VxeButton,VxeSwitch,VxeImage,VxeCheckbox,VxeInput,VxeSelect } from "vxe-pc-ui";
import { ElMessage } from "element-plus";
import type { DrawerProps } from 'element-plus';
import { copyTextToClipboard } from "@pureadmin/utils";
import  { merchantsInfoContractList,listMerchantName,taxSourcesList,contractTypeList,merchantsRemove,merchantsState,remarkList,remarkRemove,addRemarkInfo,listBackstageUser } from '@/api/contract/contract';

import {
  MerchantsInfoByTaxSourcesId,
} from "@/api/welcome";
import { downloadFile } from '@/api/file';
const reVxeGridRef = ref();
import { useRouter } from "vue-router";
import merchantsModal from './components/merchantsModal.vue'
const router = useRouter();

let taxSourcesId = Number(sessionStorage.getItem("taxSourcesId"))
onBeforeMount(()=>{
  getMerchantsInfoByTaxSourcesId( taxSourcesId )
  gettypelist();
})
onMounted(() => {
  getalllist();
  getmerchant();
  getuserlist();
});
// 合同分类列表
const typelist = ref<any[]>()
const gettypelist = () => {
  contractTypeList().then((res:any) => {
    typelist.value = res.data;
  })
}
const listMerchantsInfoByTaxSourcesId = ref<RestaurantItem[]>([]);
const getMerchantsInfoByTaxSourcesId = (taxSourcesId?:
  number): void => {
  MerchantsInfoByTaxSourcesId(taxSourcesId).then((res: any) => {
    listMerchantsInfoByTaxSourcesId.value = res.data;
  });
};
// 创建人列表
const userList = ref<any[]>();
const getuserlist = ()=>{
  listBackstageUser({entrySide: 3}).then((res: any) => {
    userList.value = res.data.rows;
  })
}
// // 税源地
const allList = ref<any[]>()
const getalllist = ()=>{
  taxSourcesList({merchantsInfoId: formOptions.data.merchantsInfoId}).then(res=>{
    allList.value = res?.data?.rows;
  })
}
// 商户列表
const merchantList = ref<any[]>()
const getmerchant = ()=>{
  listMerchantName().then(res=>{
    merchantList.value = res?.data?.rows;
  })
}
const recordId = ref();
const columns: VxeGridPropTypes.Columns<any> = [
  // { type: "checkbox", title: "", width: 60, align: "center" },
  {
    title: "合同编号",
    field: "contractNumber",
    align: "center",
    minWidth: 100,
    showOverflow: true
  },
  {
    title: "合同分类",
    field: "contractTypeDisplay",
    align: "center",
    minWidth: 100    
  },
  {
    title: "合作公司名称",
    field: "merchantsInfoIdDisplay",
    align: "center",
    minWidth: 100
  },
  
  {
    title: "费率",
    field: "commissionRate",
    align: "center",
    minWidth: 100,
    slots: {
      default: ({row})=>{
        return `${row.commissionRate}%`
      }
    }
  },
  {
    title: "营业执照",
    field: "businessLicenseAddress",
    align: "center",
    minWidth: 100,
    slots: {
      default: ({ row }) => {
        if (row.businessLicenseAddress) {
          return h(VxeImage, {
            src: `${row.businessLicenseAddress}`,
            width: "100",
          });
        }
      }
    }
  },
  {
    title: "签署方式",
    field: "contractSignTypeDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "客户方",
    field: "signA",
    align: "center",
    minWidth: 100,
    slots: {
      default: ({row})=>{
        return h(VxeCheckbox, {
          modelValue: row.signA ? row.signA : false,
          disabled: row.signA ? row.signA : false,
          checkedValue: true,
          uncheckedValue: false,
          onChange(res:any) {
            if(res.value){
              row.signA = res?.value;
              changeState({signA: res.value,id: row.id})
            }
          }
        })
      }
    }
  },
  {
    title: "我方",
    field: "signB",
    align: "center",
    minWidth: 150,
    slots: {
      default: ({row})=>{
        return [h(VxeCheckbox, {
          modelValue: row.signB ? row.signB : false,
          disabled: row.signB ? row.signB : false,
          checkedValue: true,
          uncheckedValue: false,
          onChange(res:any) {
            if (res?.value && !row.postNo) {
              ElMessage.error("请输入快递编号！");
              return false;
            }
            row.signB = res?.value;
            if(res.value){
              changeState({signB: res.value,id: row.id,postNo: row.postNo})
            }
          }
        }),h(VxeInput, {
          modelValue: row.postNo,
          readonly: row.signB ? row.signB : false,
          placeholder: '快递单号',
          onInput(res:any) {
            row.postNo = res?.value;
          }
        })]
      }
    }
  },
  {
    title: "合同状态",
    field: "contractStateDisplay",
    align: "center",
    minWidth: 100
  },
  {
    title: "合同开始时间",
    field: "contractSignTimeStart",
    align: "center",
    minWidth: 100
  },
  {
    title: "合同到期时间",
    field: "contractSignTimeEnd",
    align: "center",
    minWidth: 100
  },
  {
    title: "创建时间",
    field: "createTime",
    align: "center",
    minWidth: 100
  },
  // {
  //   title: "备注",
  //   field: "remark",
  //   align: "center",
  //   fixed: `right`,
  //   minWidth: 200,
  //   slots: {
  //     default: ({row})=>{
  //       return h(VxeButton, {
  //         status: "primary",
  //         mode: "text",
  //         size: "mini",
  //         content: "更多",
  //         onClick() {
  //           recordId.value = row.id;
  //           getremark({remarkType: 1,recordId: row.id});
  //         }
  //       })
  //     }
  //   }
  // },
  {
    title: "操作",
    field: "operate",
    align: "center",
    fixed: `right`,
    minWidth: 300,
    slots: {
      default: ({ row }) => {
        let list = [h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "甲方签约链接",
              onClick() {
                if(!row.signUrlA){
                  ElMessage.error("链接地址不存在！");
                }
                if(row.signUrlA){                  
                 handleCopy(row.signUrlA);
                }
              }
            }),
            h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "乙方签约链接",
              onClick() {
                if(!row.signUrlB){
                  ElMessage.error("链接地址不存在！");
                }
                if(row.signUrlB){                  
                  handleCopy(row.signUrlB);
                }
              }
            }),
            h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "word下载",
              onClick() {
                if(!row.contractTemplateAddressBack){
                  ElMessage.error("下载地址不存在！");
                  return false;
                }
                let index = row.contractTemplateAddressBack.lastIndexOf("/");
                let filename = row.contractTemplateAddressBack.substring(
                  index + 1,
                  row.contractTemplateAddressBack.length
                );
                downloadFile(row.contractTemplateAddressBack, "", "get", filename);
              }
            }),h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "下载",
              onClick() {
                if(!row.contractTemplateAddress){
                  ElMessage.error("下载地址不存在！");
                  return false;
                }
                let index = row.contractTemplateAddress.lastIndexOf("/");
                let filename = row.contractTemplateAddress.substring(
                  index + 1,
                  row.contractTemplateAddress.length
                );
                downloadFile(row.contractTemplateAddress, "", "get", filename);
              }
            }),h(VxeButton, {
              status: "primary",
              mode: "text",
              size: "mini",
              content: "查看",
              onClick() {
                if(!row.contractTemplateAddress){
                  ElMessage.error("查看地址不存在！");
                  return false;
                }
                window.open(row.contractTemplateAddress, "_blank");
              }
            })]
        if(row.contractSignType == 2){ //签署方式：线下          
            return [list[2],list[3],list[4]]
          
        }else if(row.contractSignType == 1){//签署方式：线上
            if(row.contractState == 2){ //签署状态 ：已完成
              return [list[0],list[2],list[3],list[4]];
            }else if(row.contractState == 1){//签署状态 ：一方签署
               return [list[0],list[2]];
            }else if(row.contractState == 0){ //签署状态 ：未签署
               return [list[0],list[1],list[2]];
            }
        }
      }
    }
  }
];
const changeState = (param: any)=>{
  merchantsState(param).then(res => {
    handleSearch();
  })
}
// 筛选相关
const formRef = ref();
interface FormDataVO {
  contractNumber: string;//合同编号
  taxSourcesId: number | string; // 税源地
  merchantsInfoId: number | string; //商户id
  contractType: number | string; // 合同分类
  contractSignType: number | string; // 签署方式
  contractState: number | string; // 合同状态
  contractSignTimeStart: string;//合同开始日期
  contractSignTimeEnd: string;//合同结束日期
  deptId: string | number; //所属代理
  createTimeStart: number | string; //开始日期
  createTimeEnd: number | string; //结束日期
  timeRang: string[]; //日期数组
}
const formOptions = reactive<VxeFormProps<FormDataVO>>({
  data: {
    contractNumber: '',
    taxSourcesId: taxSourcesId,
    merchantsInfoId: '',
    contractType: '',
    contractSignType: '',
    contractState: '',
    contractSignTimeStart: '',
    contractSignTimeEnd: '',
    deptId: '',
    createTimeStart: "",
    createTimeEnd: "",
    timeRang: [],
  },
  items: [
    {
      field: "contractNumber",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "contractNumber" }
    },
    {
      field: "contractType",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "contractType" }
    },
    {
      field: "merchantsInfoId",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "merchantsInfoId" }
    },    
    {
      field: "contractSignType",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "contractSignType" }
    },
    {
      field: "contractState",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "contractState" }
    },
    {
      field: "contractSignTimeStart",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "contractSignTimeStart" }
    },
    {
      field: "contractSignTimeEnd",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "contractSignTimeEnd" }
    },
    {
      field: "timeRang",
      title: "",
      span: 4,
      itemRender: {},
      slots: { default: "timeRang" }
    },
    { align: "left", span: 4, slots: { default: "active" } }
  ]
});
// 签署方式
const signTypelist = ref<any[]>([{
  value: 1,
  label: '电子签署'
}, {
  value: 2,
  label: '线下签署'
}])
// 合同状态
const stateOptions = ref<any[]>([{
  value: 0,
  label: '未签署'
}, {
  value: 1,
  label: '一方签署'
}, {
  value: 2,
  label: '已完成'
}])

// 重置内容
const handleInitialFormParams = () => {
  formOptions.data = <FormDataVO>{
    taxSourcesId: '',
    merchantsInfoId: ''
  };
};
const handleSearch = () => {
  if (formOptions.data?.timeRang?.length) {
    formOptions.data.createTimeStart = formOptions.data.timeRang[0];
    formOptions.data.createTimeEnd = formOptions.data.timeRang[1];
  } else {
    formOptions.data.createTimeStart = "";
    formOptions.data.createTimeEnd = "";
  }
  reVxeGridRef.value.loadData();
};
const handleReset = async () => {
  await handleInitialFormParams();
  reVxeGridRef.value.loadData("reset");
};

const handleAdd = () => {
  
};
  const handleCopy = async (text) => {
  const success = await copyTextToClipboard(text);
  if (success) {
    ElMessage.success("复制成功！");
  }
}
const merchantsModalRef = ref();
const handleEdit = (record: Recordable) => {
  merchantsModalRef.value.showEditModal(record);
};

const handleDelete = async (record: Recordable) => {
  const type = await VxeUI.modal.confirm("您确定要删除吗？");
  if (type == "confirm") {
    merchantsRemove(record.id).then(() => {
      handleSearch();
    });
  }
};

const handleView = (record: Recordable) => {
  
};
const functions: Record<string, string> = {
  add: "platform.client.index.add",
  edit: "platform.client.index.edit",
  view: "platform.client.index.view",
  delete: "platform.client.index.delete"
};

// 时间戳转
// function formatDate (time) {//时间戳转日期
//     let date = new Date(time);
//     let y = date.getFullYear();
//     let MM = date.getMonth() + 1;
//     MM = MM < 10 ? ('0' + MM) : MM;
//     let d = date.getDate();
//     d = d < 10 ? ('0' + d) : d;
//     let h = date.getHours();
//     h = h < 10 ? ('0' + h) : h;
//     let m = date.getMinutes();
//     m = m < 10 ? ('0' + m) : m;
//     let s = date.getSeconds();
//     s = s < 10 ? ('0' + s) : s;
//     return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
//     // return y + '-' + MM + '-' + d;
// }

// 备注
const remarkAll = ref<any[]>();
const getremark = (param: any)=>{
  remarkList(param).then((res: any) => {
    remarkAll.value = res.data.rows;
    remarkDrawer.value = true;
  })
}
// 备注 
const direction = ref<DrawerProps['direction']>('rtl')
const remarkDrawer = ref(false)
const remarkText = ref();
const addremark = () => {
  if(remarkText.value){
    addRemarkInfo({
      recordId: recordId.value,
      remark: remarkText.value,
      remarkType: 1
    }).then(res => {
      remarkText.value = '';
      getremark({remarkType: 1,recordId: recordId.value});
    })
  }
  
}
const todeleteone = (index: number,item:any)=>{
  remarkRemove(item.id).then(res=>{
    remarkAll.value.splice(index,1)
  })
}
</script>
<template>
  <div>
    <el-card :shadow="`never`">
      <vxe-form ref="formRef" v-bind="formOptions">
        <template #contractNumber="{ data }">
          <el-input
            clearable
            placeholder="合同编号"
            v-model="data.contractNumber"
          ></el-input>
        </template>
        <template #contractType="{ data }">
          <el-select
            clearable
            placeholder="合同分类"
            v-model="data.contractType"
          >
            <el-option
              v-for="(item, index) in typelist"
              :key="index"
              :label="item.desc"
              :value="item.code"
            ></el-option>
          </el-select>
        </template>
        <template #merchantsInfoId="{ data }">
          <el-select
            clearable
            placeholder="请选择商户名称"
            v-model="data.merchantsInfoId"
          >
            <el-option
              v-for="(item, index) in listMerchantsInfoByTaxSourcesId"
              :key="index"
              :label="item.value"
              :value="item.id"
            ></el-option>
          </el-select>
        </template>
        <template #contractSignType="{ data }">
          <el-select
            clearable
            placeholder="签署方式"
            v-model="data.contractSignType"
          >
            <el-option
              v-for="(item, index) in signTypelist"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
        <template #contractState="{ data }">
          <el-select
            clearable
            placeholder="合同状态"
            v-model="data.contractState"
          >
            <el-option
              v-for="(item, index) in stateOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
        <template #contractSignTimeStart="{ data }">
          <el-date-picker
            clearable
            style="width: 100%"
            v-model="data.contractSignTimeStart"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="合同开始时间"
          />
        </template>
        <template #contractSignTimeEnd="{ data }">
          <el-date-picker
            clearable
            style="width: 100%"
            v-model="data.contractSignTimeEnd"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="合同结束时间"
          />
        </template>       
        <template #timeRang="{ data }">
          <el-date-picker
            clearable
            style="width: 100%"
            v-model="data.timeRang"
            type="daterange"
            range-separator="-"
            value-format="YYYY-MM-DD"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </template>
        <template #active>
          <el-button @click="handleSearch" native-type="submit" type="primary"
            >搜索</el-button
          >
          <el-button @click="handleReset" native-type="reset">重置</el-button>          
        </template>
      </vxe-form>
      <!-- <div class="mt-3">
        <el-button @click="handleAdd" plain type="primary">新建类目</el-button>
      </div> -->
    </el-card>
    <el-card :shadow="`never`" class="table-card">
      <ReVxeGrid
        ref="reVxeGridRef"
        :request="merchantsInfoContractList"
        :functions="functions"
        :searchParams="formOptions.data"
        :columns="columns"
        :action="false"
        @handleAdd="handleAdd"
        @handleView="handleView"
        @handleDelete="handleDelete"
      />
    </el-card>
    
    <merchantsModal ref="merchantsModalRef" @reload="handleSearch"></merchantsModal>
    <el-drawer v-model="remarkDrawer" :direction="direction">
      <template #header>
        <h4>备注历史</h4>
      </template>
      <template #default>
        <div>
          <div v-for="(item,index) in remarkAll" :key="index" class="flex justify-between items-start remark">
            <div class="remarkUser">
              {{item.userName}}
            </div>
            <div class="remarkContent pl-3">
              <div class="flex justify-start items-center">
                <div class="mr-2">{{item.createTime}}</div>
                <el-button @click="todeleteone(index,item)" size="small" type="danger" plain>删除备注</el-button>
              </div>
              <div class="mt-3">
                {{item.remark}}
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-input type="textarea" show-word-limit maxlength="200" v-model="remarkText" style="width: 350px;" placeholder="请输入备注内容" />
          <el-button style="margin-left: 30px;" type="primary" @click="addremark">提交</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<style>
.form_header {
  font-size: 15px;
  color: #6379bb;
  border-bottom: 1px solid #ddd;
  padding-bottom: 5px;
}
.left-title {
  font-weight: 700;
  font-family: 微软雅黑;
  font-size: 14px;
  width: 85px;
  text-align: right;
}
.right-text {
  font-size: 14px;
}



.avatar-uploader .el-upload {
  border: 1px dashed #eee;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: #eee;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 138px;
  height: 138px;
  text-align: center;
}
.avatar {
  width: 138px;
  height: 138px;
}
.e_footer {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  background: #fff;
}
.remark{
  border-top: 1px solid #ccc;
  line-height: 32px;
  padding: 20px 30px;
}
.remarkUser{
  font-size: 18px;
  color: #1890ff;
  font-weight: 600;
}
.remarkContent{
  flex: 1;

}
</style>
